/**
 * 统计数据状态Store
 */
const { observable, action } = require('mobx-miniprogram');
const statisticsRepository = require('../services/statistics_repository');
const Day = require('dayjs');

export const statisticsStore = observable({
  // 状态定义
  loading: false,
  error: null,
  projectStatistics: null, // 完整项目统计
  progressStatistics: null, // 进度统计
  tasksStatistics: null, // 任务统计
  resourcesStatistics: null, // 资源统计
  risksStatistics: null, // 风险统计
  dashboardStatistics: [], // 数据看板统计（多项目）
  period: 'week', // 当前统计周期
  dateRange: { // 日期范围
    start: Day().subtract(30, 'day').format('YYYY-MM-DD'),
    end: Day().format('YYYY-MM-DD')
  },
  
  /**
   * 获取项目统计数据
   * @param {String} projectId 项目ID
   * @param {Object} params 查询参数
   */
  async getProjectStatistics(projectId, params = {}) {
    if (!projectId) return;
    
    this.loading = true;
    this.error = null;
    
    try {
      // 合并参数
      const queryParams = { 
        period: this.period,
        startDate: this.dateRange.start,
        endDate: this.dateRange.end,
        ...params 
      };
      
      // 调用仓储层
      const statistics = await statisticsRepository.getProjectStatistics(projectId, queryParams);
      
      // 更新状态
      this.projectStatistics = statistics;
      this.loading = false;
      
      return statistics;
    } catch (err) {
      this.error = err.message || '获取项目统计数据失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 获取项目进度统计
   * @param {String} projectId 项目ID
   * @param {Object} params 查询参数
   */
  async getProjectProgress(projectId, params = {}) {
    if (!projectId) return;
    
    this.loading = true;
    this.error = null;
    
    try {
      // 合并参数
      const queryParams = { 
        period: this.period,
        startDate: this.dateRange.start,
        endDate: this.dateRange.end,
        ...params 
      };
      
      // 调用仓储层
      const statistics = await statisticsRepository.getProjectProgress(projectId, queryParams);
      
      // 更新状态
      this.progressStatistics = statistics;
      this.loading = false;
      
      return statistics;
    } catch (err) {
      this.error = err.message || '获取项目进度统计失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 获取项目任务统计
   * @param {String} projectId 项目ID
   * @param {Object} params 查询参数
   */
  async getProjectTasks(projectId, params = {}) {
    if (!projectId) return;
    
    this.loading = true;
    this.error = null;
    
    try {
      // 合并参数
      const queryParams = { 
        period: this.period,
        startDate: this.dateRange.start,
        endDate: this.dateRange.end,
        ...params 
      };
      
      // 调用仓储层
      const statistics = await statisticsRepository.getProjectTasks(projectId, queryParams);
      
      // 更新状态
      this.tasksStatistics = statistics;
      this.loading = false;
      
      return statistics;
    } catch (err) {
      this.error = err.message || '获取项目任务统计失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 获取项目资源统计
   * @param {String} projectId 项目ID
   * @param {Object} params 查询参数
   */
  async getProjectResources(projectId, params = {}) {
    if (!projectId) return;
    
    this.loading = true;
    this.error = null;
    
    try {
      // 合并参数
      const queryParams = { 
        period: this.period,
        startDate: this.dateRange.start,
        endDate: this.dateRange.end,
        ...params 
      };
      
      // 调用仓储层
      const statistics = await statisticsRepository.getProjectResources(projectId, queryParams);
      
      // 更新状态
      this.resourcesStatistics = statistics;
      this.loading = false;
      
      return statistics;
    } catch (err) {
      this.error = err.message || '获取项目资源统计失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 获取项目风险统计
   * @param {String} projectId 项目ID
   * @param {Object} params 查询参数
   */
  async getProjectRisks(projectId, params = {}) {
    if (!projectId) return;
    
    this.loading = true;
    this.error = null;
    
    try {
      // 合并参数
      const queryParams = { 
        period: this.period,
        startDate: this.dateRange.start,
        endDate: this.dateRange.end,
        ...params 
      };
      
      // 调用仓储层
      const statistics = await statisticsRepository.getProjectRisks(projectId, queryParams);
      
      // 更新状态
      this.risksStatistics = statistics;
      this.loading = false;
      
      return statistics;
    } catch (err) {
      this.error = err.message || '获取项目风险统计失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 生成项目周期报告
   * @param {String} projectId 项目ID
   * @param {Object} params 生成参数
   */
  async generateProjectReport(projectId, params = {}) {
    if (!projectId) return;
    
    this.loading = true;
    this.error = null;
    
    try {
      // 合并参数
      const reportParams = { 
        period: this.period,
        startDate: this.dateRange.start,
        endDate: this.dateRange.end,
        ...params 
      };
      
      // 调用仓储层
      const result = await statisticsRepository.generateProjectReport(projectId, reportParams);
      
      this.loading = false;
      
      return result;
    } catch (err) {
      this.error = err.message || '生成报告失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 获取多项目数据看板统计
   * @param {Array} projectIds 项目ID数组
   * @param {Object} params 查询参数
   */
  async getDashboardStatistics(projectIds, params = {}) {
    if (!projectIds || !projectIds.length) return;
    
    this.loading = true;
    this.error = null;
    
    try {
      // 合并参数
      const queryParams = { 
        period: this.period,
        startDate: this.dateRange.start,
        endDate: this.dateRange.end,
        ...params 
      };
      
      // 调用仓储层
      const statistics = await statisticsRepository.getDashboardStatistics(projectIds, queryParams);
      
      // 更新状态
      this.dashboardStatistics = statistics;
      this.loading = false;
      
      return statistics;
    } catch (err) {
      this.error = err.message || '获取数据看板统计失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 设置统计周期
   * @param {String} period 统计周期 week|month|quarter|year|custom
   */
  setPeriod: action(function(period) {
    if (!period) return;
    
    this.period = period;
    
    // 根据周期自动设置日期范围
    const today = Day();
    
    switch (period) {
      case 'week':
        this.dateRange = {
          start: today.subtract(7, 'day').format('YYYY-MM-DD'),
          end: today.format('YYYY-MM-DD')
        };
        break;
      case 'month':
        this.dateRange = {
          start: today.subtract(30, 'day').format('YYYY-MM-DD'),
          end: today.format('YYYY-MM-DD')
        };
        break;
      case 'quarter':
        this.dateRange = {
          start: today.subtract(90, 'day').format('YYYY-MM-DD'),
          end: today.format('YYYY-MM-DD')
        };
        break;
      case 'year':
        this.dateRange = {
          start: today.subtract(365, 'day').format('YYYY-MM-DD'),
          end: today.format('YYYY-MM-DD')
        };
        break;
      // custom周期不自动设置日期范围
    }
  }),
  
  /**
   * 设置日期范围
   * @param {String} start 开始日期
   * @param {String} end 结束日期
   */
  setDateRange: action(function(start, end) {
    if (start) this.dateRange.start = start;
    if (end) this.dateRange.end = end;
  }),
  
  /**
   * 重置统计数据
   */
  resetStatistics: action(function() {
    this.projectStatistics = null;
    this.progressStatistics = null;
    this.tasksStatistics = null;
    this.resourcesStatistics = null;
    this.risksStatistics = null;
    this.dashboardStatistics = [];
  })
}); 